
package aa.jx.cartFunction.controller;

import aa.jx.cartFunction.model.Cart;
import aa.jx.cartFunction.model.CartItemDTO;
import aa.jx.cartFunction.model.CartProductDTO;
import aa.jx.cartFunction.service.CartService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/api/cart")
public class CartController {

    private final CartService cartService;

    @Autowired
    public CartController(CartService cartService) {
        this.cartService = cartService;
    }

    @PostMapping("/setUserId")
    public ResponseEntity<?> setUserId(@RequestParam("userId") Integer userId, HttpServletRequest request) {
        if (userId == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }

        HttpSession session = request.getSession();
        session.setAttribute("userId", userId);
        return ResponseEntity.ok().body("用户ID已设置到Session");
    }

    @PostMapping("/add")
    public ResponseEntity<?> addToCart(@RequestBody Cart cart, HttpServletRequest request) {
        HttpSession session = request.getSession();
        Integer sessionUserId = (Integer) session.getAttribute("userId");

        if (cart.getProductId() == null) {
            return ResponseEntity.badRequest().body("商品ID不能为空");
        }

        if (cart.getQuantity() == null || cart.getQuantity() <= 0) {
            cart.setQuantity(1);
        }

        // 优先使用Session中的userId
        if (sessionUserId != null) {
            cart.setUserId(sessionUserId);
        } else if (cart.getUserId() == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }

        try {
            Cart newCart = cartService.addCart(cart);
            return new ResponseEntity<>(newCart, HttpStatus.CREATED);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("添加购物车失败: " + e.getMessage());
        }
    }

    @DeleteMapping("/delete/{id}")
    public ResponseEntity<?> deleteCartItem(
            @PathVariable("id") Integer cartItemId,
            @RequestParam(value = "userId", required = false) Integer userId,
            HttpServletRequest request) {

        HttpSession session = request.getSession();
        Integer sessionUserId = (Integer) session.getAttribute("userId");

        if (cartItemId == null || (userId == null && sessionUserId == null)) {
            return ResponseEntity.badRequest().body("参数不能为空");
        }

        Integer finalUserId = userId != null ? userId : sessionUserId;

        boolean success = cartService.deleteCartItem(cartItemId, finalUserId);

        if (success) {
            return ResponseEntity.ok().body("删除成功");
        } else {
            return ResponseEntity.status(HttpStatus.NOT_FOUND)
                    .body("购物车项不存在或无权删除");
        }
    }

    @DeleteMapping("/clearCart")
    public ResponseEntity<?> clearCart(
            @RequestParam(value = "userId", required = false) Integer userId,
            HttpServletRequest request) {

        HttpSession session = request.getSession();
        Integer sessionUserId = (Integer) session.getAttribute("userId");

        if (userId == null && sessionUserId == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }

        Integer finalUserId = userId != null ? userId : sessionUserId;

        boolean success = cartService.clearCart(finalUserId);

        if (success) {
            return ResponseEntity.ok().body("购物车已清空");
        } else {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("清空购物车失败");
        }
    }

    @GetMapping("/selectCart")
    public ResponseEntity<?> selectCartItems(
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam(value = "productName", required = false) String productName,
            HttpServletRequest request) {

        HttpSession session = request.getSession();
        Integer sessionUserId = (Integer) session.getAttribute("userId");

        if (userId == null && sessionUserId == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }

        Integer finalUserId = userId != null ? userId : sessionUserId;

        try {
            List<CartItemDTO> cartItems = cartService.getCartItems(finalUserId, productName);
            return ResponseEntity.ok(cartItems);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("查询购物车失败: " + e.getMessage());
        }
    }

    @GetMapping("/cartProductsList")
    public ResponseEntity<?> getCartProducts(
            @RequestParam(value = "userId", required = false) Integer userId,
            HttpServletRequest request) {

        HttpSession session = request.getSession();
        Integer sessionUserId = (Integer) session.getAttribute("userId");

        if (userId == null && sessionUserId == null) {
            return ResponseEntity.badRequest().body("用户ID不能为空");
        }

        Integer finalUserId = userId != null ? userId : sessionUserId;

        try {
            List<CartProductDTO> cartProducts = cartService.getCartProducts(finalUserId);
            return ResponseEntity.ok(cartProducts);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("查询购物车商品失败: " + e.getMessage());
        }
    }

    @PutMapping("/updateQuantity")
    public ResponseEntity<?> updateCartQuantity(
            @RequestParam("cartId") Integer cartId,
            @RequestParam(value = "userId", required = false) Integer userId,
            @RequestParam("quantity") Integer quantity,
            HttpServletRequest request) {

        HttpSession session = request.getSession();
        Integer sessionUserId = (Integer) session.getAttribute("userId");

        if (cartId == null || quantity == null || (userId == null && sessionUserId == null)) {
            return ResponseEntity.badRequest().body("参数不能为空");
        }

        if (quantity < 0) {
            return ResponseEntity.badRequest().body("数量不能为负");
        }

        Integer finalUserId = userId != null ? userId : sessionUserId;

        try {
            Cart updatedCart = cartService.updateCartQuantity(cartId, finalUserId, quantity);
            return ResponseEntity.ok(updatedCart);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("更新数量失败: " + e.getMessage());
        }
    }

    @GetMapping("/getCartById")
    public ResponseEntity<?> getCartById(@RequestParam("cartId") Integer cartId) {
        try {
            Cart cartItem = cartService.getCartById(cartId);
            if (cartItem == null) {
                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("购物车项不存在");
            }
            return ResponseEntity.ok(cartItem);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("查询失败: " + e.getMessage());
        }
    }

    @PostMapping("/logout")
    public ResponseEntity<?> logout(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session != null) {
            session.invalidate();
        }
        return ResponseEntity.ok().body("已登出");
    }


    @GetMapping("/items")
    public ResponseEntity<?> getCartItemsByIds(@RequestParam("ids") List<Integer> ids) {
        try {
            List<CartProductDTO> items = cartService.getCartItemsByIds(ids);
            return ResponseEntity.ok(items);
        } catch (Exception e) {
            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
                    .body("获取购物车商品失败: " + e.getMessage());
        }
    }









}



















//package aa.jx.cartFunction.contraller;
//
//
//
//import aa.jx.cartFunction.model.Cart;
//import aa.jx.cartFunction.mapper.CartMapper;
//import aa.jx.cartFunction.model.CartItemDTO;
//import aa.jx.cartFunction.model.CartProductDTO;
//import aa.jx.cartFunction.service.CartService;
//import jakarta.servlet.http.HttpServletRequest;
//import jakarta.servlet.http.HttpSession;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.web.bind.annotation.*;
//
//import java.util.List;
//import java.util.Map;
///**
// * 购物车Controller
// */
//
//@RestController
//@RequestMapping("/api/cart")
//public class CartController {
//
//    private final CartService cartService;
//
//    @Autowired
//    public CartController(CartService cartService)
//    {
//        this.cartService=cartService;
//    }
//
//    @PostMapping("/add")
//    public ResponseEntity<?> addToCart(@RequestBody Cart cart) {
//        if (cart.getUserId() == null || cart.getProductId() == null) {
//            return ResponseEntity.badRequest().body("用户ID和商品ID不能为空");
//        }
//        if (cart.getQuantity() == null || cart.getQuantity() <= 0) {
//            cart.setQuantity(1); // 设置默认值
//        }
//
//        try {
//            Cart newCart = cartService.addCart(cart);
//            return new ResponseEntity<>(newCart, HttpStatus.CREATED);
//        } catch (Exception e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body("添加购物车失败: " + e.getMessage());
//        }
//
////        Cart newCart = cartService.addCart(cart);
////        return new ResponseEntity<>(newCart, HttpStatus.CREATED);
//    }
//
//    // 新增删除方法
//    @DeleteMapping("/delete/{id}")
//    public ResponseEntity<?> deleteCartItem(
//            @PathVariable("id") Integer cartItemId,
//            @RequestParam("userId") Integer userId) {
//
//        if (cartItemId == null || userId == null) {
//            return ResponseEntity.badRequest().body("参数不能为空");
//        }
//
//        boolean success = cartService.deleteCartItem(cartItemId, userId);
//
//        if (success) {
//            return ResponseEntity.ok().body("删除成功");
//        } else {
//            return ResponseEntity.status(HttpStatus.NOT_FOUND)
//                    .body("购物车项不存在或无权删除");
//        }
//    }
//
//    // 新增清空购物车方法
//    @DeleteMapping("/clearCart")
//    public ResponseEntity<?> clearCart(@RequestParam("userId") Integer userId) {
//        if (userId == null) {
//            return ResponseEntity.badRequest().body("用户ID不能为空");
//        }
//
//        boolean success = cartService.clearCart(userId);
//
//        if (success) {
//            return ResponseEntity.ok().body("购物车已清空");
//        } else {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body("清空购物车失败");
//        }
//    }
//
//
//    // 新增查询方法
//    @GetMapping("/selectCart")
//    public ResponseEntity<?> selectCartItems(
//            @RequestParam("userId") Integer userId,
//            @RequestParam(value = "productName", required = false) String productName) {
//
//        if (userId == null) {
//            return ResponseEntity.badRequest().body("用户ID不能为空");
//        }
//
//        try {
//            List<CartItemDTO> cartItems = cartService.getCartItems(userId, productName);
//            return ResponseEntity.ok(cartItems);
//        } catch (Exception e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body("查询购物车失败: " + e.getMessage());
//        }
//    }
//
//    // 获取列表方法
//    @GetMapping("/cartProductsList")
//    public ResponseEntity<?> getCartProducts(@RequestParam("userId") Integer userId) {
//        if (userId == null) {
//            return ResponseEntity.badRequest().body("用户ID不能为空");
//        }
//
//        try {
//            List<CartProductDTO> cartProducts = cartService.getCartProducts(userId);
//            return ResponseEntity.ok(cartProducts);
//        } catch (Exception e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body("查询购物车商品失败: " + e.getMessage());
//        }
//    }
//
//
//    // 增加减少数量修改
//    // 修改更新数量的方法，允许数量为0
//    @PutMapping("/updateQuantity")
//    public ResponseEntity<?> updateCartQuantity(
//            @RequestParam("cartId") Integer cartId,
//            @RequestParam("userId") Integer userId,
//            @RequestParam("quantity") Integer quantity) {
//
//        if (cartId == null || userId == null || quantity == null) {
//            return ResponseEntity.badRequest().body("参数不能为空");
//        }
//        if (quantity < 0) {  // 允许数量为0
//            return ResponseEntity.badRequest().body("数量不能为负");
//        }
//
//        try {
//            Cart updatedCart = cartService.updateCartQuantity(cartId, userId, quantity);
//            return ResponseEntity.ok(updatedCart);
//        } catch (Exception e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body("更新数量失败: " + e.getMessage());
//        }
//    }
//
//    //添加获取单个购物车项
//    @GetMapping("/getCartById")
//    public ResponseEntity<?> getCartById(@RequestParam("cartId") Integer cartId) {
//        try {
//            Cart cartItem = cartService.getCartById(cartId);
//            if (cartItem == null) {
//                return ResponseEntity.status(HttpStatus.NOT_FOUND).body("购物车项不存在");
//            }
//            return ResponseEntity.ok(cartItem);
//        } catch (Exception e) {
//            return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)
//                    .body("查询失败: " + e.getMessage());
//        }
//    }
//
////xinzeng
//    // 新增：设置用户ID到Session
//    @PostMapping("/setUserId")
//    public ResponseEntity<?> setUserId(@RequestParam("userId") Integer userId, HttpServletRequest request) {
//        if (userId == null) {
//            return ResponseEntity.badRequest().body("用户ID不能为空");
//        }
//
//        HttpSession session = request.getSession();
//        session.setAttribute("userId", userId);
//        return ResponseEntity.ok().body("用户ID已设置到Session");
//    }
//
//
//
//
//
//}
